const socket = io();

let currentUserId = '';
let currentNickname = '';


function loginUser() {
  clearFormMessage('loginFormMessage');
  const id = document.getElementById('loginId').value.trim(), pwd = document.getElementById('loginPassword').value;
  if (!id || !pwd) {
    showFormMessage('用户 ID 和密码不能为空', 'error', 'loginFormMessage');
    return;
  }
  const pwdHash = CryptoJS.SHA256(pwd).toString();
  socket.emit('login', { userId: id, password: pwdHash });
}



socket.on('loginResult', ({ success, message, nickname, userId, avatar }) => {
  if (success) {
    showToast('登录成功，欢迎 ' + nickname, 'success');
    localStorage.setItem('userId', userId);
    localStorage.setItem('nickname', nickname);
    localStorage.setItem('avatar', avatar);
    socket.emit('online', {userId, nickname});
    // socket.join(userId);
    setTimeout(() => location.href = 'home.html', 800);
  } else {
    showFormMessage(message || '登录失败', 'error', 'loginFormMessage');
  }
});


function registerUser() {
  const id = document.getElementById('registerId').value.trim();
  const nick = document.getElementById('registerNickname').value.trim();
  const email = document.getElementById('registerEmail').value.trim();
  const pwd = document.getElementById('registerPassword').value;
  const pwdHash = CryptoJS.SHA256(pwd).toString();

  const cpwd = document.getElementById('confirmPassword').value;

  // 清除旧提示
  clearFormMessage('registerFormMessage');

  // 前端校验
  if (!id || !nick || !email || !pwd || !cpwd) {
    showFormMessage('请将所有字段填写完整', 'error', 'registerFormMessage');
    return;
  }

  if (id.length < 5 || id.length > 20) {
    showFormMessage('id长度须在5~20之间', 'error', 'registerFormMessage');
    return;
  }

  if (pwd.length < 9 || pwd.length > 20) {
    showFormMessage('密码长度须在9~20之间', 'error', 'registerFormMessage');
    return;
  }

  if (nick.length > 20) {
    showFormMessage('昵称长度不得超过20', 'error', 'registerFormMessage');
    return;
  }

  if (pwd !== cpwd) {
    showFormMessage('两次密码不一致','error','registerFormMessage');
    return;
  }

  var pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  if (!pattern.test(email)) {
    showFormMessage('邮箱格式不合法','error','registerFormMessage');
    return;
  }

  // 发给后端
  socket.emit('register', { userId: id, nickname: nick, email, password: pwdHash });
}

socket.on('registerResult', ({ success, message }) => {
  if (success) {
    showToast('注册成功，请登录', 'success');
    // 自动切到登录 Tab
    setTimeout(() => {
      document.querySelector('[data-target="login"]').click();
      // 重置注册表单
      document.getElementById('register').reset();
      clearFormMessage('registerFormMessage');
    }, 800);
  } else {
    showFormMessage(message || '注册失败', 'error', 'registerFormMessage');
  }
});



/**
 * 在页面顶部显示浮层通知，2 秒后自动消失
 * @param {string} msg    文本内容
 * @param {'success'|'error'} type 类型
 */
function showToast(msg, type = 'error') {
  const container = document.getElementById('toastContainer');
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.textContent = msg;
  container.appendChild(toast);

  // 触发动画
  setTimeout(() => toast.classList.add('show'), 10);

  // 2.5s 后消失并移除
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => container.removeChild(toast), 300);
  }, 2500);
}

/**
 * 在表单顶部区域内联显示提示
 * @param {string} msg 文本内容
 * @param {'success'|'error'} type 类型
 * @param {string} [elementId='formMessage'] 提示容器 id
 */
function showFormMessage(msg, type = 'error', elementId = 'formMessage') {
  const fm = document.getElementById(elementId);
  if (!fm) return;
  fm.textContent = msg;
  fm.className = `form-message ${type}`;
}

/**
 * 隐藏表单内联提示
 * @param {string} [elementId='formMessage'] 提示容器 id
 */
function clearFormMessage(elementId = 'formMessage') {
  const fm = document.getElementById(elementId);
  if (!fm) return;
  fm.className = 'form-message hidden';
}


window.addEventListener('DOMContentLoaded', () => {
  // 切换 Tab（只改 class，不改 style）
  document.querySelectorAll('.tab-btn').forEach(btn =>
    btn.addEventListener('click', () => {
      document
        .querySelectorAll('.tab-btn')
        .forEach(b => b.classList.remove('active'));
      btn.classList.add('active');

      document
        .querySelectorAll('.form-section')
        .forEach(f => f.classList.add('hidden'));
      document
        .getElementById(btn.dataset.target)
        .classList.remove('hidden');
    })
  );

  // 自动跳转
  if (localStorage.getItem('userId') && localStorage.getItem('nickname')) {
    location.replace('home.html');
  }
});